<?php
function auto_url(){
	if (isset($_SERVER['HTTP_HOST']))
	{
		$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
		$base_url .= '://'. $_SERVER['HTTP_HOST'];
		$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
	}

	else
	{
		$base_url = 'http://localhost/';
	}
	return $base_url;
}
function is_crsf($url) {
	if(strpos($url, '://') === false) {
		//
	} else {
		if(strpos($url, VG::$config['cookie_domain'] ? VG::$config['cookie_domain'] : VG::$config['base_url']) === false) return false;
	}
	return preg_match("/(\?|\&|\.php)/i", $url);
}
function multi_input_merge(){
	$n=func_num_args();
	if($n<=1) return array();
	$arr=array();
	$a=func_get_arg(0);
	foreach($a[1] as $k=>$v){
		$arr[$k]=array();
		$arr[$k][$a[0]]=$v;
		foreach(range(1,$n-1) as $kk=>$vv){
			$b=func_get_arg($vv);
			$arr[$k][$b[0]]=$b[1][$k];
		}
	}
	return $arr;
}
function array_dimension_change($data,$kind='2->1',$key=array()){
	if($kind=='2->1'){
		return call_user_func_array('array_merge_recursive',$data);
	} else if($kind=='1->2'){
		array_unshift($data,null);
		$t=call_user_func_array('array_map',$data);
		if(count($key)){
			$res=array();
			foreach($t as $k=>$v) $res[]=array_combine($key,$v);
			return $res;
		}else{
			return $t;
		}
	}
	return false;
}
function array_save($array,$file) {
	$data = var_export($array,true);
	$data = "<?php\n return ".$data.';';
	return file_put_contents($file,$data);
}
function kv_builder($arr,$id,$name,$add=array(),$prefix=array()){
    $res=array();
	if(count($prefix)){
		foreach((array) $prefix as $v) $res[$v[0]]=$v[1];
	}
    foreach((array) $arr as $v) $res[$v[$id]]=$v[$name];
	if(count($add)){
		foreach((array) $add as $v) $res[$v[0]]=$v[1];
	}
    return $res;
}
function ka_builder($arr,$id,$name='*',$add=array()){
    $res=array();
	$name_arr=explode(',',$name);
    foreach((array) $arr as $v){
		if($name_arr[0]=='*'){
			$res[$v[$id]]=$v;
		}else{
			$tmp=array();
			foreach($v as $kk=>$vv){
				if(in_array($kk,$name_arr)) $tmp[$kk]=$vv;
			}
			$res[$v[$id]]=$tmp;
		}
	}
	if(count($add)){
		foreach((array) $add as $v) $res[$v[0]]=$v;
	}
    return $res;
}
function kc_builder($arr,$name,$add=array()){
    $res=array();
    foreach((array) $arr as $v) $res[]=$v[$name];
	if(count($add)){
		foreach((array) $add as $v) $res[]=$v;
	}
    return $res;
}
function ks_builder($arr,$id,$name='*',$sep='-',$add=array()){
    $res=array();
	$name_arr=explode(',',$name);
    foreach((array) $arr as $v){
		if($name_arr[0]=='*'){
			$res[$v[$id]]=implode($sep,$v);
		}else{
			$tmp=array();
			foreach($v as $kk=>$vv){
				if(in_array($kk,$name_arr)) $tmp[$kk]=$vv;
			}
			$res[$v[$id]]=implode($sep,$tmp);
		}
	}
	if(count($add)){
		foreach((array) $add as $v) $res[$v[0]]=$v[1];
	}
    return $res;
}
function smart_url($arr=array()){
    isset($arr['pjt']) or $arr['pjt']=VG::$pjt;
    isset($arr['module']) or $arr['module']=VG::$module;
    isset($arr['control']) or $arr['control']=VG::$control;
    isset($arr['action']) or $arr['action']=VG::$action;
    isset($arr['get']) or $arr['get']='';
    return url($arr['pjt'].'/'.$arr['module'].'/'.$arr['control'].'/'.$arr['action'],$arr['get']);
}
function auto_get($except=array()){
	$p_url=$_SERVER['QUERY_STRING'];
	parse_str($p_url,$arr);
	foreach($except as $k=>$v){
		if(array_key_exists($v,$arr)){
			unset($arr[$v]);
		}
	}
	return http_build_query($arr);
}
function warning($msg=''){
	echo "<h2 style='text-align:center;border:1px solid #ccc;margin:60px;padding:60px;color:red;'>{$msg}</h2>";
	exit;
}
function msg($result,$msg='',$url=''){
    include(APPPATH.'views/back/msg.php');
	exit;
}
function addslashes_array($string) { 
	if(is_array($string)) { 
		foreach($string as $key => $val) { 
			$string[$key] = addslashes_array($val); 
		} 
	} else { 
		$string = addslashes(trim($string)); 
	} 
	return $string; 
}
function stripslashes_array($string) {
	if (is_array($string)) {
		foreach ($string as $k => $v) {
			$string[$k] = stripslashes_array($v);
		}
	} else if (is_string($string)) {
		$string = stripslashes($string);
	}
	return $string;
}
function load_memcache(){
	static $mem=null;
	if($mem) return $mem;
	//启用memcache缓存
	if(!empty(VG::$config['memServers'])){
		//判断memcache扩展是否安装
		if(extension_loaded("memcache")){
			$mem=new MemcacheModel(VG::$config['memServers']);
			//判断Memcache服务器是否有异常
			if(!$mem->mem_connect_error()){
				exit("连接memcache服务器失败,请检查!");
			}
			return $mem;
		}else{
			exit("PHP没有安装memcache扩展模块,请先安装!");
		}	
	}else{
		exit("请在配置文件中添加memServers");
	}
}
function load_view($name,$path='',$var=array()){
	if($path==''){
		$f=APPPATH.'views/'.$name.'.php';
	}else{
		$f=$path.$name.'.php';
	}
	if(file_exists($f)){
		extract($var);
		include($f);
	}else{
		exit($name.'view不存在');
	}
}
function load_lang(){
	
}
function load_setting($moduleid){
	$setting_file=APPPATH.'setting/'.$moduleid.'.php';
	$setting=array();
	if(file_exists($setting_file)){
		$setting=include($setting_file);
	}
	return $setting;
}
function save_setting($moduleid,$post){
	$setting_file=APPPATH.'setting/'.$moduleid.'.php';
	if($post){
		$str="<?php\r\n";
		$str.='return ';
		$str.=var_export($post,true);
		$str.=';';
		return file_put_contents($setting_file, $str);
	}
	return false;
}
function load_library(){
	
}
function load_module_helper($name,$path=''){
	$pjt=VG::$uri[0];
	$module=VG::$uri[1];
	if($path==''){
		$f=APPPATH.'controllers/'.$pjt.'/'.$module.'/helpers/'.$name.'Helper.class.php';
	}else{
		$f=$path.$name.'Helper.class.php';
	}
	if(file_exists($f)){
		include_once($f);
	}else{
		exit($name.'module helper不存在');
	}
	$class=$name.'Helper';
	if(class_exists($class)){
		return new $class;
	}
	exit($class.'module helper类名无效');
}
function load_service($name,$path=''){
	if($path==''){
		$name=trim($name,'/');
		$dir=explode('/',$name);
		$name=array_pop($dir);
		$p=implode('/',$dir)?implode('/',$dir).'/':'';
		$f=APPPATH.'services/'.$p.$name.'Service.class.php';
	}else{
		$f=$path.$name.'Service.class.php';
	}
	if(file_exists($f)){
		include_once($f);
	}else{
		exit($name.'service不存在');
	}
	$class=$name.'Service';
	if(class_exists($class)){
		return new $class;
	}
	exit($class.'service类名无效');
}
function M($className=null,$path=''){
	if($path==''){
		$file=APPPATH.'models/'.$className.'Model.class.php';
	}else{
		$file=$path.$className.'Model.class.php';
	}	
	if(is_null($className)){
		$model=new Model();
		return $model->getConnection();
	}else{
		$className=strtolower($className);
		$modelName=$className.'Model';
		if(!file_exists($file)){
			$model=new Model();
			$data=$model->getConnection()->setTableAddon(VG::$db['dbprefix'].$className);
			$pk=$data['pk'];
$str=<<<st
<?php
class {$modelName} extends Model{
	public \$primaryKey='{$pk}';
	public \$table='{$className}';
	
	public function __construct(){
		parent::__construct();
		
		\$this->_auto = array();
		\$this->_valid = array();
		\$this->_valid_for_add = array();
		\$this->_valid_for_mod = array();
		\$this->_valid_for_select = array();
		
	}

}
st;
			$r=file_put_contents($file,$str);
			if(!$r) exit("{$modelName} 写入失败！");
		}
		return load_model($className,$path);
	}
}
function S($className=null,$path=''){
	if($path==''){
		$file=APPPATH.'services/'.$className.'Service.class.php';
	}else{
		$file=$path.$className.'Service.class.php';
	}	
	if(is_null($className)){
		return false;
	}else{
		$className=strtolower($className);
		$modelName=$className.'Service';
		if(!file_exists($file)){
			
$str=<<<st
<?php
class {$modelName} extends Service{
	
	public function __construct(){
		parent::__construct();
		
		
		
	}

}
st;
			$r=file_put_contents($file,$str);
			if(!$r) exit("{$modelName} 写入失败！");
		}
		return load_service($className,$path);
	}
}
function H($name,$path='',$subfix=''){
	$pjt=VG::$uri[0];
	$module=VG::$uri[1];
	if($path==''){
		$f=APPPATH.'controllers/'.$pjt.'/'.$module.'/helpers/'.$name.'Helper.class.php';
	}else{
		$f=$path.$name.'Helper.class.php';
	}
	$name=strtolower($name);
	$helperName=$name.'Helper';
	if(!file_exists($f)){
		
$str=<<<st
<?php
class {$helperName} extends stdlib{$subfix}{

public function __construct(){
	parent::__construct();
	
	
	
}

}
st;
		$r=file_put_contents($f,$str);
		if(!$r) exit("{$helperName} 写入失败！");
	}
	return load_module_helper($name,$path);
	
}

function load_model($name,$path=''){
	if($path==''){
		$name=trim($name,'/');
		$dir=explode('/',$name);
		$name=array_pop($dir);
		$p=implode('/',$dir)?implode('/',$dir).'/':'';
		$f=APPPATH.'models/'.$p.$name.'Model.class.php';
	}else{
		$f=$path.$name.'Model.class.php';
	}
	if(file_exists($f)){
		include_once($f);
	}else{
		exit($name.'model不存在');
	}
	$class=$name.'Model';
	if(class_exists($class)){
		return new $class;
	}
	exit($class.'model类名无效');
}
function alert($msg){
	echo "<script>alert('{$msg}');</script>";
}
function autoalert($f,$extra=''){
	if($f){
		alert("操作成功！\\n{$extra}");
	}else{
		alert("操作失败！\\n{$extra}");
	}
}
function jump($r,$get=''){
    if($get) $get='&'.$get;
    echo "<script>window.location.href='?r={$r}{$get}';</script>";
    exit;
}
function back(){
    echo "<script>window.history.back();</script>";
    exit;
}
function reload($t='parent'){
	if($t=='parent'){
		echo '<script>window.parent.location.reload();</script>';
	}else{
		echo '<script>window.location.reload();</script>';
	}
	exit;
}
function js($code){
	echo '<script>';
	echo $code;
	echo '</script>';
}
function url($r,$get=''){
    if($get) $get='&'.$get;
	return "?r={$r}{$get}";
}
function p(){
	$args=func_get_args();  //获取多个参数
	if(count($args)<1){
		return;
	}	
	echo '<div style="width:100%;text-align:left"><pre>';
	//多个参数循环输出
	foreach($args as $arg){
		if(is_array($arg)){  
			print_r($arg);
			echo '<br>';
		}else if(is_string($arg)){
			echo $arg.'<br>';
		}else{
			var_dump($arg);
			echo '<br>';
		}
	}
	echo '</pre></div>';	
}
function pe(){
	$args=func_get_args();  //获取多个参数
	if(count($args)<1){
		return;
	}	
	echo '<div style="width:100%;text-align:left"><pre>';
	//多个参数循环输出
	foreach($args as $arg){
		if(is_array($arg)){  
			print_r($arg);
			echo '<br>';
		}else if(is_string($arg)){
			echo $arg.'<br>';
		}else{
			var_dump($arg);
			echo '<br>';
		}
	}
	echo '</pre></div>';	
	exit;
}
function myswitch($kvalue,$array){
	return  $array[$kvalue];
}
//二维数组转一维
function multi2single($array){
	$new_array=array();
	$keys=array_keys($array[0]);
	$size=count($keys);
	$n=count($array);
	for($i=0;$i<$n;$i++){
		for($j=0;$j<$size;$j++){
			$key_name=$keys[$j];
			$new_array[$key_name][]=$array[$i][$key_name];
		}
	}
	return $new_array;
}
//二维转一维 单元素
function multi2single_min($array,$key_name){
	$new_array=array();
	if(!is_array($array)) return array();
	if(!is_array($array[0])) return array();
	$n=count($array);
	for($i=0;$i<$n;$i++){
		$new_array[]=$array[$i][$key_name];
	}
	return $new_array;
}
function set_cookie($var,$value='',$time=0){
	$conf=VG::$config;
	$time=$time>0?$time:(empty($value)?time()-3600:0);
	$var=$conf['cookie_prefix'].$var;
	return setcookie($var,$value,$time,$conf['cookie_path'],$conf['cookie_domain'],$conf['cookie_secure']);
}
function get_cookie($var) {
	$conf=VG::$config;
	$var=$conf['cookie_prefix'].$var;
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : '';
}
function dsubstr($string, $length, $suffix = '', $start = 0, $charset='utf-8') {
	if($start) {
		$tmp = dsubstr($string, $start);
		$string = substr($string, strlen($tmp));
	}
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array('&quot;', '&lt;', '&gt;'), array('"', '<', '>'), $string);
	$length = $length - strlen($suffix);
	$str = '';
	if(strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < $strlen)	{
			$t = ord($string{$n});
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) break;
		}
		if($noc > $length) $n -= $tn;
		$str = substr($string, 0, $n);
	} else {
		for($i = 0; $i < $length; $i++) {
			$str .= ord($string{$i}) > 127 ? $string{$i}.$string{++$i} : $string{$i};
		}
	}
	$str = str_replace(array('"', '<', '>'), array('&quot;', '&lt;', '&gt;'), $str);
	return $str == $string ? $str : $str.$suffix;
}
function unique(){
	return substr(md5(rand(1000,9999)),5,8);
}
// function site_url($s=''){
	// $conf=VG::$config;
	// return $conf['base_url'].$s;
// }
// function app_url($s=''){
	// $conf=VG::$config;
	// $app=str_replace('./','',APPPATH);
	// return $conf['base_url'].$app.$s;
// }
function static_url($s=''){
	$conf=VG::$config;
	$app=str_replace('./','',APPPATH);
	$pjt=VG::$uri[0];
	return $conf['base_url'].$app.'static/'.$pjt.'/'.$s;
}
function tosize($bytes) {       	 	     
	if ($bytes >= pow(2,40)) {      		     
		$return = round($bytes / pow(1024,4), 2);    
		$suffix = "TB";                        	    
	} elseif ($bytes >= pow(2,30)) {  		     
		$return = round($bytes / pow(1024,3), 2);    
		$suffix = "GB";                             
	} elseif ($bytes >= pow(2,20)) {  		     
		$return = round($bytes / pow(1024,2), 2);
		$suffix = "MB";                             
	} elseif ($bytes >= pow(2,10)) {  		     
		$return = round($bytes / pow(1024,1), 2);
		$suffix = "KB";                              
	} else {                     			     
		$return = $bytes;                            
		$suffix = "Byte";                           
	}
	return $return ." " . $suffix;
}
//echo form_radio('tag',array(1=>'显示',0=>'隐藏',2=>'很好'),1);
function form_radio($name,$array,$checked='-1',$id_prefix='x_'){
	$string='';
   foreach($array as $key=>$value){
		if($checked==$key){
			$c="checked='checked'";
		}else{
			$c='';
		}
		$string.=<<<st
\n\r<label><input type="radio" name="{$name}" value="{$key}" {$c} id='{$id_prefix}{$key}' />{$value}</label>
st;
   }
   return $string."\r\n";
}
//echo form_checkbox('mycheckbox',array(0=>'音乐',1=>'体育',2=>'政治'),array(1,2));
function form_checkbox($name,$array,$checked=array(),$id_prefix='y_'){
	$string='';
	foreach($array as $key=>$value){
		if(in_array($key,$checked)){
			$c="checked='checked'";
		}else{
			$c='';
		}
		$string.=<<<st
\n\r<label><input type="checkbox" name="{$name}" value="{$key}" {$c} id='{$id_prefix}{$key}' />{$value}</label>
st;
   }
   return $string."\r\n";
}
//echo form_select(array(0=>'第0个',1=>'第一个',2=>'第二个'),2);
function form_select($array,$selected='-1'){
	$string='';
	foreach($array as $key=>$value){
		if($selected==$key){
			$s="selected='selected'";
		}else{
			$s='';
		}
		$string.=<<<st
\n\r<option value='{$key}' {$s} >{$value}</option>
st;
	}
	return $string."\r\n";
}
function dcalendar($name, $value = '', $sep = '-') {
	global $destoon_calendar_id;
	$calendar = '';
	$id = str_replace(array('[', ']'), array('', ''), $name);
	if(!$destoon_calendar_id) {
		$destoon_calendar_id = 1;
		$calendar .= '<script type="text/javascript" src="/common/js/calendar.js"></script>';
	}
	$calendar .= '<input class="input" type="text" name="'.$name.'" id="'.$id.'" value="'.$value.'" size="10" onfocus="ca_show(\''.$id.'\', this, \''.$sep.'\');" readonly ondblclick="this.value=\'\';"/> <img src="/common/images/calendar/calendar.gif" align="absmiddle" onclick="ca_show(\''.$id.'\', this, \''.$sep.'\');" style="cursor:pointer;"/>';
	$calendar .= " [<span onclick=\"ca_clear('{$id}');\">置空</span>]";
	return $calendar;
}
function get_area_select($title = '', $areaid = 0, $extend = '', $deep = 0, $id = 1) {
	$model=load_model('area');
	$parents = array();
	if($areaid) {
		$r=	$model->field('child,arrparentid')->where(array('areaid'=>$areaid))->easy_find();
		$parents = explode(',', $r['arrparentid']);
		if($r['child']) $parents[] = $areaid;
	} else {
		$parents[] = 0;
	}
	$select = '';
	foreach($parents as $k=>$v) {
		if($deep && $deep <= $k) break;
		$v = intval($v);
		$select .= '<select onchange="load_area(this.value, '.$id.');" '.$extend.'>';
		if($title) $select .= '<option value="0">'.$title.'</option>';
		
		$data=$model->field('areaid,areaname')->where(array('parentid'=>$v))->order('listorder,areaid asc')->easy_select();
		foreach($data as $a) {
			$selectid = isset($parents[$k+1]) ? $parents[$k+1] : $areaid;
			$selected = $a['areaid'] == $selectid ? ' selected' : '';
			$select .= '<option value="'.$a['areaid'].'"'.$selected.'>'.$a['areaname'].'</option>';
		}
		$select .= '</select> ';
	}
	return $select;
}

function ajax_area_select($name = 'areaid', $title = '', $areaid = 0, $extend = '', $deep = 0) {
	global $area_id;
	if($area_id) {
		$area_id++;
	} else {
		$area_id = 1;
	}
	$areaid = intval($areaid);
	$deep = intval($deep);
	$select = '';
	$select .= '<input name="'.$name.'" id="areaid_'.$area_id.'" type="hidden" value="'.$areaid.'"/>';
	$select .= '<span id="load_area_'.$area_id.'">'.get_area_select($title, $areaid, $extend, $deep, $area_id).'</span>';
	$select .= '<script type="text/javascript">';
	if($area_id == 1) $select .= 'var area_title = new Array;';
	$select .= 'area_title['.$area_id.']=\''.$title.'\';';
	if($area_id == 1) $select .= 'var area_extend = new Array;';
	$select .= 'area_extend['.$area_id.']=\''.$extend.'\';';
	if($area_id == 1) $select .= 'var area_areaid = new Array;';
	$select .= 'area_areaid['.$area_id.']=\''.$areaid.'\';';
	if($area_id == 1) $select .= 'var area_deep = new Array;';
	$select .= 'area_deep['.$area_id.']=\''.$deep.'\';';
	$select .= '</script>';
	if($area_id == 1) $select .= '<script type="text/javascript" src="/common/js/area.js"></script>';
	return $select;
}

/**
 * sys_file_cache 数据缓存及存取程序
 * 
 * @param dir       缓存目录
 * @param method    数据存取模式，取值"w"为存入数据，取值"r"读取数据，取值"c"为删除数据
 * @param name    标识数据的名称
 * @param value    存入的值，在读取数据和删除数据的模式下均为NULL
 * @param life_time    变量的生存时间，默认为永久保存
 */
function sys_file_cache($dir, $method, $name, $value = NULL, $life_time = -1){
	// 准备缓存目录和缓存文件名称，缓存文件名称为$name的MD5值，文件后缀为php
	$dir=trim($dir,'/').'/'.substr(md5($name),0,2).'/';
	if(!is_dir($dir))mkdir($dir,0777,true);
	$sfile = $dir.md5($name).".php";
	// 对$method进行判断，分别进行读写删的操作
	if('w' == $method){ 
		// 写数据，在$life_time为-1的时候，将增大$life_time值以令$life_time不过期
		$life_time = ( -1 == $life_time ) ? '300000000' : $life_time;
		// 准备存入缓存文件的数据，缓存文件使用PHP的die();函数以便保证内容安全，
		$value = '<?php die();?>'.( time() + $life_time ).serialize($value); // 数据被序列化后保存
		return file_put_contents($sfile, $value);
	}elseif('c' == $method){
		// 清除数据，直接移除改缓存文件
		return @unlink($sfile);
	}else{
		// 读数据，检查文件是否可读，同时将去除缓存数据前部的内容以返回
		if( !is_readable($sfile) )return FALSE;
		$arg_data = file_get_contents($sfile);
		// 获取文件保存的$life_time，检查缓存是否过期
		if( substr($arg_data, 14, 10) < time() ){
			@unlink($sfile); // 过期则移除缓存文件，返回FALSE
			return FALSE;
		}
		return unserialize(substr($arg_data, 24)); // 数据反序列化后返回
	}
}

function template_compile($from, $to) {
	$content = template_parse(file_get_contents($from));
	file_put_contents($to, $content);
}

function template_parse($str) {
	$str = preg_replace("/\<\!\-\-\[(.+?)\]\-\-\>/", "", $str);
	$str = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $str);
	$str = preg_replace("/\{template\s+([^\}]+)\}/", "<?php include template(\\1);?>", $str);
	$str = preg_replace("/\{php\s+(.+)\}/", "<?php \\1?>", $str);
	$str = preg_replace("/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str);
	$str = preg_replace("/\{else\}/", "<?php } else { ?>", $str);
	$str = preg_replace("/\{elseif\s+(.+?)\}/", "<?php } else if(\\1) { ?>", $str);
	$str = preg_replace("/\{\/if\}/", "<?php } ?>\r\n", $str);
	$str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) { foreach(\\1 as \\2) { ?>", $str);
	$str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>", $str);
	$str = preg_replace("/\{\/loop\}/", "<?php } } ?>", $str);
	$str = preg_replace("/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str);
	$str = preg_replace_callback("/<\?php([^\?]+)\?>/s", "template_addquote1", $str);
	$str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\+\-\x7f-\xff]*)\}/", "<?php echo \\1;?>", $str);
	$str = preg_replace_callback("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\+\-\x7f-\xff]+)\}/s", "template_addquote2", $str);
	$str = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str);
	$str = preg_replace("/\'([A-Za-z]+)\[\'([A-Za-z\.]+)\'\](.?)\'/s", "'\\1[\\2]\\3'", $str);
	$str = preg_replace("/(\r?\n)\\1+/", "\\1", $str);
	$str = str_replace("\t", '', $str);
	$str = "<?php defined('APPPATH') or exit('Access Denied');?>".trim($str);
	return $str;
}

function template_addquote1($matches) {
	return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9\-\.\x7f-\xff]+)\]/s", "['\\1']", $matches[0]));
}

function template_addquote2($matches) {
	return '<?php echo '.str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9\-\.\x7f-\xff]+)\]/s", "['\\1']", $matches[1])).';?>';
}


function template($data=array(),$template='') {
	if($template){
		$basename=$template;
		$from=APPPATH.'views/'.$template.'.php';
	}else{
		$basename=VG::$current_route;
		$from=VG::$view_file;
	}
	$to = APPPATH.'runtime/tpl/'.$basename.'.php';
	$isfileto = is_file($to);
	
	if(!file_exists($from)) exit("{$basename} 模板文件不存在");

	if(!$isfileto || filemtime($from) > filemtime($to) || (filesize($to) == 0 && filesize($from) > 0)) {
		$dir=dirname($to);
		if(!file_exists($dir)) mkdir($dir,0777,true);
		template_compile($from, $to);
	}
	return $to;
}
